﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Intergr8.Data.Query
{
    /// <summary>
    /// Engine to perform the parsing
    /// </summary>
    public class Engine
    {
        private ClauseCollection _clauses = new ClauseCollection();

        public void ParseQuery(string query)
        {           
            // Clear out the clause collection
            _clauses.Clear();

            // Extract out all the Clauses in the query
            ExtractClauses(query);

            // Run through the Clauses and update with the corresponding criteria
            if (_clauses.Count > 0)
            {
                Clause lastClause = _clauses[_clauses.Keys.ElementAt(0)];
                foreach (Clause c in _clauses.Values)
                {
                    // If this is the next clause in the list
                    if (!c.Type.Equals(lastClause.Type))
                    {
                        int startindex = lastClause.Index+ lastClause.Type.Length;
                        int endindex = c.Index;

                        _clauses[lastClause.Type].Items = query.Substring(startindex , (endindex - startindex)).Trim();


                        // Set the last clause to this one
                        lastClause = c;
                    }
                }
            }

        }

        private void ExtractClauses(string query)
        {
            string strFindClause = "";

            // Find SELECT/select
            strFindClause = "SELECT";
            Clause select = new Clause(strFindClause, query.IndexOf(strFindClause, StringComparison.CurrentCultureIgnoreCase));
            _clauses.Add(select.Type, select);

            // Find WHERE/where
            strFindClause = "WHERE";
            Clause where = new Clause(strFindClause, query.IndexOf(strFindClause, StringComparison.CurrentCultureIgnoreCase));
            _clauses.Add(where.Type, where);
        }

        public ClauseCollection Clauses
        {
            get { return _clauses; }
        }
    }
}
